package com.futvan.z.system.zjob;

import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.core.SuperService;
import com.futvan.z.framework.core.z;
import com.futvan.z.framework.util.JobUtil;
import com.futvan.z.framework.util.SystemUtil;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.HashMap;
@Service
public class ZjobService extends SuperService{

	public Result start_job(HashMap<String, String> bean){
		Result result = new Result();
		String JobId = bean.get("zid");
		z_job job = selectBean("select * from z_job where zid = '"+JobId+"'",z_job.class);
		//判断参数是否为空
		if(z.isNotNull(JobId)) {
			try {
				//添加任务，如果出异常返回错误
				JobUtil.jobAdd(job);
				result.setCode(Code.SUCCESS);
				//变更任务状态
				int num = update("update z_job set isstart = '1' where zid = '"+JobId+"'");
				if(num!=1) {
					//删除已启动的任务
					JobUtil.jobDelete(JobId);
					z.Exception("变更任务状态出错");
				}
			} catch (Exception e) {
				result.setCode(Code.ERROR);
				result.setMsg(e.getMessage());
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("JobId is null");
		}
		return result;
	}



	public Result close_job(HashMap<String, String> bean) {
		Result result = new Result();
		String JobId = bean.get("zid");
		//判断参数是否为空
		if(z.isNotNull(JobId)) {
			try {
				//变更任务状态
				int num = update("update z_job set isstart = '0' where zid = '"+JobId+"'");
				if(num==1) {
					//删除任务，如果出异常返回错误
					JobUtil.jobDelete(JobId);
					result.setCode(Code.SUCCESS);
				}else {
					z.Exception("变更任务状态出错");
				}
			} catch (Exception e) {
				result.setCode(Code.ERROR);
				result.setMsg(e.getMessage());
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("/start_job error JobId  is null");
		}
		return result;
	}

	public Result run_job(HashMap<String, String> bean) {
		Result result = new Result();
		String JobId = bean.get("zid");

		//判断参数是否为空
		if(z.isNotNull(JobId)) {
			try {
				z_job job = selectBean("select * from z_job where zid = '"+JobId+"'",z_job.class);
				if(z.isNull(job.getJobtime())) {
					job.setJobtime("0 * * * * ?");
				}
				//执行任务，如果出异常返回错误
				JobUtil.jobRun(job);
				result.setCode(Code.SUCCESS);
			} catch (Exception e) {
				result.setCode(Code.ERROR);
				result.setMsg(e.getMessage());
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("/start_job error JobId is null");
		}
		return result;
	}



	/**
	 * 生成任务类文件
	 * @param bean
	 * @param request 
	 * @return
	 * @throws Exception 
	 */
	public Result create_job_class(HashMap<String, String> bean) throws Exception {
		Result result = new Result();
		String zid = bean.get("zid");
		if(z.isNotNull(zid)) {
			z_job job = selectBean("z_job_select_zid", zid);
			if(z.isNotNull(job)) {
				//判读任务执行文件字段是否为空
				if(z.isNull(job.getJobclass())) {
					String jobclass = bean.get("jobclass");
					if(z.isNull(jobclass) ) {
						jobclass = "com.futvan.z.job.Temp"+z.newZcode()+"Job";
					}
					int num = update("update z_job set jobclass = '"+jobclass+"' where zid = '"+zid+"'");
					if(num!=1) {
						z.Exception("生成任务类文件过程中，更新jobclass字段出错，执行SQL返回结果不等于1");
					}
					if(num==1) {
						job = selectBean("z_job_select_zid", zid);
					}
				}
				//生成文件
				result = CreateJobClassFile(job);
			}else {
				result.setCode(Code.ERROR);
				result.setData(zid);
				result.setMsg("请先保存任务记录，然后生成任务类文件");
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("zid is null");
		}
		return result;
	}



	/**
	 * 生成文件
	 * @param job 任务
	 * @throws IOException 
	 */
	private Result CreateJobClassFile(z_job job) throws IOException {
		Result result = new Result();
		//先判读是否是开发环境，如是是开发环境，在生成java类
		if(SystemUtil.isIDE()) {
			//Eclipse开发环境
			String project_path = z.sp.get("project_path");//源码路径
			File f = new File(project_path+"\\src\\main\\java\\"+job.getJobclass().replace(".", "\\")+".java");
			//判读目录是否创建
			if(!f.getParentFile().exists()) {
				f.getParentFile().mkdirs();
			}
			//如果找到文件删除
			if (!f.exists()) {
				//创建文件
				f.createNewFile();

				//创建输入流
				OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
				BufferedWriter writer = new BufferedWriter(write);
				writer.write("package "+job.getJobclass().substring(0, job.getJobclass().lastIndexOf("."))+";\n");
				writer.write("import org.quartz.JobExecutionContext;\n");
				writer.write("import org.quartz.JobExecutionException;\n");
				writer.write("import org.quartz.StatefulJob;\n");
				writer.write("/**\n");
				writer.write(" * 任务程序："+job.getJobname()+"\n");
				writer.write(" */\n");
				writer.write("public class "+job.getJobclass().substring(job.getJobclass().lastIndexOf(".")+1)+" implements StatefulJob{\n");
				writer.write("	\n");
				writer.write("	public void execute(JobExecutionContext context) throws JobExecutionException {\n");
				writer.write("		\n");
				writer.write("	}\n");
				writer.write("}\n");
				writer.close();
				write.close();
				
				result.setCode(Code.SUCCESS);
				result.setData(job.getZid());
				result.setMsg("生成任务类文件成功");
			}else {
				result.setCode(Code.ERROR);
				result.setData(job.getZid());
				result.setMsg("任务类文件已生成");
			}
		}else {
			result.setCode(Code.ERROR);
			result.setData(job.getZid());
			result.setMsg("非开发环境，无法生成任务类文件");
		}
		return result;
	}

}
